package com.heatup.apt.api.service.impl;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.heatup.apt.api.controller.pay.util.PropertiesUtil;
import com.heatup.apt.api.controller.pay.util.message.Article;
import com.heatup.apt.api.controller.pay.util.message.CustomserviceUtil;
import com.heatup.apt.api.controller.pay.util.message.MessageUtil;
import com.heatup.apt.api.controller.pay.util.message.NewsMessage;
import com.heatup.apt.api.service.CouponService;
import com.heatup.apt.api.service.DataDictService;
import com.heatup.apt.api.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.heatup.apt.api.controller.pay.util.message.CustomerServiceMessage;
import com.heatup.apt.api.controller.pay.util.message.TextMessage;
import com.heatup.apt.api.service.CoreService;
import com.heatup.apt.api.service.InviteCouponService;
import com.heatup.apt.common.constants.DataDictConstants;
import com.heatup.apt.common.dao.ActivityInfoMapper;
import com.heatup.apt.common.dao.ActivityUserMapper;
import com.heatup.apt.common.dao.ChannerDetailedMapper;
import com.heatup.apt.common.dao.ChannerQrcodeMapper;
import com.heatup.apt.common.dao.CouponDetailMapper;
import com.heatup.apt.common.dao.CouponInfoMapper;
import com.heatup.apt.common.dao.OrderInfoMapper;
import com.heatup.apt.common.dao.TokenMapper;
import com.heatup.apt.common.dao.VipPurchaseLogMapper;
import com.heatup.apt.common.dao.redis.UserPositionRedisDao;
import com.heatup.apt.common.dao.user.UserInfoMapper;
import com.heatup.apt.model.DataDict;
import com.heatup.apt.model.channer.ChannerDetailed;
import com.heatup.apt.model.channer.ChannerQrcode;
import com.heatup.apt.model.coupon.ActivityInfo;
import com.heatup.apt.model.coupon.ActivityUser;
import com.heatup.apt.model.coupon.CouponInfo;
import com.heatup.apt.model.user.UserInfo;

/**
 * 微信时间接口实现类
 * 
 * @author jixiangyun 2016年11月24日 上午12:28:55
 */
@Service
public class CoreServiceImpl  implements CoreService {

	private static final Logger logger = LoggerFactory.getLogger(CoreServiceImpl.class);

	@Autowired
	private ChannerQrcodeMapper channerQrcodeMapper;
	
	@Autowired
	private ChannerDetailedMapper channerDetailedMapper;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserInfoMapper userInfoMapper;
	
	@Autowired
	private ActivityInfoMapper activityInfoMapper;
	
	@Autowired
	private CouponInfoMapper couponInfoMapper;
	
	@Autowired
	private CouponService couponService;
	
	@Autowired
	private UserPositionRedisDao userPositionRedisDao;
	
	@Autowired
	private ActivityUserMapper activityUserMapper;
	
	@Autowired
	private TokenMapper tokenMapper;
	
	@Autowired
	private OrderInfoMapper orderInfoMapper;
	
	@Autowired
	private CouponDetailMapper couponDetailMapper;
	
	@Autowired
	private VipPurchaseLogMapper vipPurchaseLogMapper;
	
	@Autowired
	private InviteCouponService inviteCouponService;
	
	@Autowired
    DataDictService dataDictService;
	
	
	@Override
	public String processRequest(HttpServletRequest request,HttpServletResponse response) {
		Map<String, String> requestMap = null; 
		// 用户的opendId
		String fromUserName = null;
		// 公众帐号
		String toUserName = null;
		// 消息类型
		String msgType = null;
		// 事件类型
		String eventType = null;
		// 推送消息
		String respMessage = "";
		try {
			requestMap = MessageUtil.parseXml(request);
			fromUserName = requestMap.get("FromUserName");
			toUserName = requestMap.get("ToUserName");
			msgType = requestMap.get("MsgType");
			logger.info("===================processRequestNew： fromUserName:"+fromUserName+"=======================");
			logger.info("===================processRequestNew： toUserName"+toUserName+"=======================");
			logger.info("===================processRequestNew： msgType1:"+msgType+"=======================");
			//locationTypeMsg(request, requestMap);//获取地理位置
			// 消息推送事件
			if(MessageUtil.REQ_MESSAGE_TYPE_EVENT.trim().equals(requestMap.get("MsgType").trim())){
				eventType = requestMap.get("Event");
				logger.info("===================processRequestNew： eventType:"+eventType+"=======================");
				// 如果获取不到消息类型直接返回
				if(StringUtils.isEmpty(eventType)){
					return defaultMsg(fromUserName, toUserName);
				}
				// 关注
				if(MessageUtil.EVENT_TYPE_SUBSCRIBE.trim().equals(eventType.trim())){
					// 先发送模班消息
					PrintWriter out = response.getWriter();
					try {
						String msg = defaultMsg(fromUserName, toUserName);
						logger.info("================================msg:"+msg+"=========================================");
						out.print(msg);
					} catch (Exception e) {
						logger.error(e.toString() + e.getCause());
					}finally{
						out.close();
					}
					subscribeMsg(requestMap, fromUserName, toUserName,response,request);
					fristFreeCouponActivitySendMsg(fromUserName);
					respMessage = "";
				}else if(MessageUtil.EVENT_TYPE_CLICK.trim().equals(eventType.trim())){
				// 点击菜单事件
					respMessage = clickMsg(requestMap, fromUserName, toUserName);
				}else if(MessageUtil.EVENT_TYPE_UNSUBSCRIBE.trim().equals(eventType.trim())){
				// 用户取消关注事件	
					logger.info("======================================用户取消了关注微信公众账号=====================================================");
					UserInfo userInfoOld =userService.getUserInfoByOpenId(fromUserName);
					userInfoOld.setSubscribe(0);
					userInfoOld.setVersion(userInfoOld.getVersion()+1);
					int bool = userService.updateUserInfo(userInfoOld);
					logger.info("======================================用户取消了关注微信公众账号=bool:"+bool+"================================================");
				}else if(MessageUtil.REQ_MESSAGE_TYPE_LOCATION.equals(eventType.trim()) || "LOCATION".equals(eventType.trim())){
					locationTypeMsg(request, requestMap);
				}else if("SCAN".equals(eventType.trim()) || "scan".equals(eventType.trim())){
					// 先发送末班消息
					PrintWriter out = response.getWriter();
					try {
						String msg = defaultMsg(fromUserName, toUserName);
						logger.info("================================msg:"+msg+"=========================================");
						out.print(msg);
					} catch (Exception e) {
						logger.error(e.toString() + e.getCause());
					}finally{
						out.close();
					}
					
					userScanAttention(requestMap, fromUserName, toUserName,response);
					fristFreeCouponActivitySendMsg(fromUserName);
					respMessage = "";
				}
			}
			// 文件消息回复事件
			else if(MessageUtil.REQ_MESSAGE_TYPE_TEXT.trim().equals(requestMap.get("MsgType").trim())){
				logger.info("============ in test start==============================================");
				respMessage = textMsg( requestMap.get("Content"), fromUserName, toUserName, "");
			}
			
		} catch (Exception e) {
			respMessage = defaultMsg(fromUserName, toUserName);
		}
		return respMessage;
	}
	
	/**
	 * 微信所有的事件接收和触发方法
	 */
	@Override
	public String processRequestNew(HttpServletRequest request) {
		Map<String, String> requestMap = null; 
		try {
			requestMap = MessageUtil.parseXml(request);
			String fromUserName1 = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName1 = requestMap.get("ToUserName");
			// 消息类型
			String msgType1 = requestMap.get("MsgType");
			String event1 = requestMap.get("Event");
			logger.info("===================processRequestNew： fromUserName1:"+fromUserName1+"=======================");
			logger.info("===================processRequestNew： toUserName1"+fromUserName1+"=======================");
			logger.info("===================processRequestNew： msgType1:"+msgType1+"=======================");
		} catch (Exception e) {
			// TODO: handle exception
			logger.info("===================processRequestNew： 解析文件出错了！！！！！！！！！=======================");
		}
		locationTypeMsg(request,requestMap);// 打印消息
		ActivityInfo activityInfo = activityInfoMapper.selectById(1);
		CouponInfo couponInfo =  null;//couponInfoMapper.selectByPrimaryKey(Integer.valueOf(activityInfo.getCouponId()));
		CouponInfo couponInfoI =  null;//couponInfoMapper.selectByPrimaryKey(Integer.valueOf(activityInfo.getInviteCouponId()));
		BigDecimal userA = new BigDecimal(0) ;// 邀请者可获得金额
		BigDecimal userI = new BigDecimal(0) ;// 被邀请者可获得金额
		int numA = 0 ;
		int numI = 0 ;
		if(activityInfo != null){
			String couponIds =  activityInfo.getCouponId();
			String couponId[] = couponIds.split("#");
			// 先是判断 邀请id 是否多个
			if(couponIds.indexOf("#")>0){
				for(String ids:couponId){
					couponInfo = couponInfoMapper.selectById(Integer.valueOf(ids));
					userA = userA.add(couponInfo.getCashMoney());
					numA ++;
				}
			}else{
				couponInfo = couponInfoMapper.selectById(Integer.valueOf(couponIds));
				userA = userA.add(couponInfo.getCashMoney());
				numA = 1;
			}
			String inviteCouponId = activityInfo.getInviteCouponId();
			String[] inviteCouponIds = inviteCouponId.split("#");
			// 先是判断 被邀请id 是否多个
			if(inviteCouponId.indexOf("#")>0){
				for(String ids:inviteCouponIds){
					couponInfo = couponInfoMapper.selectById(Integer.valueOf(ids));
					userI = userI.add(couponInfo.getCashMoney());
					numI ++;
				}
			}else{
				couponInfo = couponInfoMapper.selectById(Integer.valueOf(inviteCouponId));
				userI = userI.add(couponInfo.getCashMoney());
				numI = 1;
			}
			
		}
		String respMessage = "";
		logger.info("===========================================进入消息模板=========================================================");
		try {
			//Map<String, String> requestMap = MessageUtil.parseXml(request);
			logger.info("===========================================所有参数：requestMap:" + requestMap+ "=========================================================");
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			logger.info("=============================fromUserName:" + fromUserName + "=======toUserName:" + toUserName+ "=========msgType:" + msgType + "========================================");
			// 表示事件类型 关注 取消 发文 等消息事件
			String respContent = "";
			String tuis = "";
			// 响应消息
			if ("event".equals(msgType)) {
				String eventType = requestMap.get("Event");
				// 关注微信公众账号
				if ("subscribe".equals(eventType)) {
					TextMessage textMessage = new TextMessage();
					textMessage.setToUserName(fromUserName);
					textMessage.setFromUserName(toUserName);
					textMessage.setCreateTime(new Date().getTime());
					textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
					textMessage.setFuncFlag(0);
					StringBuffer contentMsg = new StringBuffer();
					logger.info("===========================================用户关注了微信公众账号=================requestMap EventKey:=====================");
					String qrscene = requestMap.get("EventKey");
					UserInfo userInfo = userService.getUserInfoByOpenId(fromUserName);
					
					if (qrscene.split("_").length>2){
						logger.error("=====================processRequestNew error===qrscene:" +qrscene+"===============================");
						qrscene = "";
					}
					
					// 关注公众账号是否是通过带参数的二维码 
					if(qrscene.length() == 0){
						logger.info("=============================首次关注公众账号 未通过渠道关注===============================");
						//
						// 首次用户
						if(userInfo == null){
							logger.info("=============================小白用户关注===============================");
							
						}else{
							logger.info("=============================首次关注的用户 InviterUserid"+userInfo.getInviterUserid()+"===============================");
							if(userInfo.getInviterUserid() != null){
								logger.info("=============================首次关注的用户 version"+userInfo.getVersion()+" "+(userInfo.getVersion() == 0)+"===============================");
								if(userInfo.getVersion() == 0){
									logger.info("=============================首次关注的用户===============================");
									UserInfo userInfoI = userService.getUserInfoById(userInfo.getInviterUserid());
									contentMsg.append("欢迎加入檬运动！").append("\n");
									contentMsg.append("您的好友"+userInfoI.getNickName()+"分享的"+numA+"张共"+userA.intValue()+"元的新人代金券将在30分钟内到账。").append("\n");
									contentMsg.append("<a href='"+String.valueOf(PropertiesUtil.get("coupon_urls")).trim()+"'>查看我的代金券</a>").append("\n");
									contentMsg.append("\n");
									contentMsg.append("当您完成第一次锻炼后,"+userInfoI.getNickName()+"也可获得"+numI+"张共"+userI.intValue()+"元的代金券").append("\n");
									contentMsg.append("<a href='"+String.valueOf(PropertiesUtil.get("course_list")).trim()+"'>我要预约课程</a>").append("\n");
								}else{
									logger.info("=============================首次关注的用户 bug===============================");
								}
								
							}
							// 关注之后再取消的用户
							else if(userInfo != null && userInfo.getVersion() == 1){
								logger.info("=============================该用户取消了之后再次关注我们的公众账号 只发送默认回复消息===============================");
							}
						}
						
						// 默认消息回复
						logger.info("=============================默认消息contentMsg.length()"+contentMsg.length()+"===============================");
						if(contentMsg.length() < 1){
							NewsMessage newsMessage = new NewsMessage();
							newsMessage.setToUserName(fromUserName);
							newsMessage.setFromUserName(toUserName);
							newsMessage.setCreateTime(new Date().getTime());
							newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
							newsMessage.setFuncFlag(0);
							// 发送图文消息
							List<Article> articleList = new ArrayList<>();
							// 图文1
							Article article1 = new Article();
							article1.setTitle("Hello, Lemon！点击查看新晋檬蜜入门指南");
							article1.setDescription("99元/月，免费撸铁、优惠团操课等你嗨！");
							article1.setPicUrl("https://mmbiz.qlogo.cn/mmbiz_jpg/028ic81tOhdhebltJibFxqPLdlXufL1O45uibIZp3VibQSOZY82z4Yb5mko2z8NXhC4kZEIrbuyIlJ7moPnzwNOicGw/0?wx_fmt=jpeg");
							article1.setUrl("http://mp.weixin.qq.com/s?__biz=MzIyMTQ5MDg2OQ==&mid=100001489&idx=1&sn=6e7871bd945c50cbac2c0026176a035f&chksm=683abd0b5f4d341dc22d5fa26f0907b2b35434c5f052a89707e80c55ac558378cb8abdf21e3f&scene=20#rd");
							
							// 图文2
							Article article2 = new Article();
							article2.setTitle("卫星大厦店全新上线 | 阳光和比基尼的午后，我要在这里运动打卡！");
							article2.setDescription("");
							article2.setPicUrl("http://gorun-h5-image.oss-cn-shenzhen.aliyuncs.com/wechat_reply_weixing.jpeg");
							article2.setUrl("http://mp.weixin.qq.com/s/BY-Ahi0Yk8LMloA0oqQxzA");
							
							articleList.add(article2);
							articleList.add(article1);
							newsMessage.setArticleCount(articleList.size());
							newsMessage.setArticles(articleList);
							textMessage.setContent(contentMsg.toString());
							respMessage = MessageUtil.newsMessageToXml(newsMessage);
							return respMessage;
							
							
						}
						textMessage.setContent(contentMsg.toString());
						// 将文本消息对象转换成xml字符串
						respMessage = MessageUtil.textMessageToXml(textMessage);
						return respMessage;
					}else{
						// 带参数的二维码
						String id = qrscene.split("_")[1];
						logger.info("=============================qrscene "+qrscene+" =id:"+id+"==============================");
						ChannerQrcode channerQrcode = channerQrcodeMapper.queryChannerQrcodeById(Integer.valueOf(id));
						if(channerQrcode != null){
							logger.info("=============================通过渠道二维码进入的微信公众账号===============================");
							int num = channerQrcode.getNumber()+1;
							channerQrcode.setNumber(num);
							//1先查询
							ChannerDetailed channerDetailed = channerDetailedMapper.queryChannerDetailedByOpendId(fromUserName);
							UserInfo userInfoNew = userInfoMapper.selectByOpenid(fromUserName);
							if(channerDetailed == null && userInfoNew == null){
								logger.info("=============================首次关注公众账号插入渠道明细信息 start===============================");
								channerDetailed = new ChannerDetailed();
								channerDetailed.setChannerId(channerQrcode.getId());
								channerDetailed.setOpenid(fromUserName);
								channerDetailed.setCreatedTime(new Date());
								int boolD = channerDetailedMapper.insertChannerDetailed(channerDetailed);
								int bool = channerQrcodeMapper.updateChannerQrcode(channerQrcode);
								logger.info("=============================首次关注公众账号插入渠道明细信息 end====boolD:"+boolD+"===bool:"+bool+"========================");
								// 插入 优惠券
								String msgs = saveCoupon(channerQrcode.getCouponId(),fromUserName,toUserName,channerQrcode,numA,numI,userA,userI,0);
								contentMsg.append(msgs).append("\n");
							}else{
								// 通过邀请好友的渠道进入微信公众账号
								if(userInfoNew.getVersion() == 0 && userInfoNew.getInviterUserid() > 0 && channerDetailed == null){
									channerDetailed = new ChannerDetailed();
									channerDetailed.setChannerId(channerQrcode.getId());
									channerDetailed.setOpenid(fromUserName);
									channerDetailed.setCreatedTime(new Date());
									int boolD = channerDetailedMapper.insertChannerDetailed(channerDetailed);
									int bool = channerQrcodeMapper.updateChannerQrcode(channerQrcode);
									logger.info("=============================首次关注公众账号插入渠道明细信息 end====boolD:"+boolD+"===bool:"+bool+"========================");
									// 插入 优惠券
									String msgs = saveCoupon(channerQrcode.getCouponId(),fromUserName,toUserName,channerQrcode,numA,numI,userA,userI,Integer.valueOf(id));
									contentMsg.append(msgs).append("\n");
								}
								logger.info("================================================渠道二维码取消关注了再次关注=====================");
							}
						}
					}
					// 默认消息回复
					logger.info("=============================默认消息contentMsg.length()"+contentMsg.length()+"===============================");
					if(contentMsg.length() == 0){
						NewsMessage newsMessage = new NewsMessage();
						newsMessage.setToUserName(fromUserName);
						newsMessage.setFromUserName(toUserName);
						newsMessage.setCreateTime(new Date().getTime());
						newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
						newsMessage.setFuncFlag(0);
						// 发送图文消息
						List<Article> articleList = new ArrayList<>();
						Article article1 = new Article();
						article1.setTitle("Hello, Lemon！点击查看新晋檬蜜入门指南");
						article1.setDescription("99元/月，免费撸铁、优惠团操课等你嗨！");
						article1.setPicUrl("https://mmbiz.qlogo.cn/mmbiz_jpg/028ic81tOhdhebltJibFxqPLdlXufL1O45uibIZp3VibQSOZY82z4Yb5mko2z8NXhC4kZEIrbuyIlJ7moPnzwNOicGw/0?wx_fmt=jpeg");
						article1.setUrl("http://mp.weixin.qq.com/s?__biz=MzIyMTQ5MDg2OQ==&mid=100001489&idx=1&sn=6e7871bd945c50cbac2c0026176a035f&chksm=683abd0b5f4d341dc22d5fa26f0907b2b35434c5f052a89707e80c55ac558378cb8abdf21e3f&scene=20#rd");
						
						// 图文2
						Article article2 = new Article();
						article2.setTitle("卫星大厦店全新上线 | 阳光和比基尼的午后，我要在这里运动打卡！");
						article2.setDescription("");
						article2.setPicUrl("http://gorun-h5-image.oss-cn-shenzhen.aliyuncs.com/wechat_reply_weixing.jpeg");
						article2.setUrl("http://mp.weixin.qq.com/s/BY-Ahi0Yk8LMloA0oqQxzA");
						
						articleList.add(article2);
						articleList.add(article1);
						newsMessage.setArticleCount(articleList.size());
						newsMessage.setArticles(articleList);
						textMessage.setContent(contentMsg.toString());
						respMessage = MessageUtil.newsMessageToXml(newsMessage);
						return respMessage;
						
					}
					
					// 当用户不存在的时候插入一条用户信息
					if(userInfo == null){
						// 插入 
						logger.info("===================user is null insert userInfo data =================================");
						userInfo = userService.wechatLogin(fromUserName, null, null, null);
					}
					userInfo.setSubscribe(1);
					int bool = userService.updateUserInfo(userInfo);
					logger.info("===================update user data bool :"+bool+"=================================");
					textMessage.setContent(contentMsg.toString());
					// 将文本消息对象转换成xml字符串
					// 由于href属性值必须用双引号引起，这与字符串本身的双引号冲突，所以要转义
					logger.info("=============================默认消息===============================");
					respMessage = MessageUtil.textMessageToXml(textMessage);
					logger.info("==============================用户关注了微信公众账号 respMessage1==" + respMessage +"=======================");
				} else if ("CLICK".equals(eventType)) {
					String eventKey = requestMap.get("EventKey");
					
					logger.info("===========================================用户点击微信公众账号菜单事件====eventKey：" + eventKey+ "=====================================================");
					// 点击联系小檬
					if("lxxm".equals(eventKey)){
						TextMessage textMessage = new TextMessage();
						textMessage.setToUserName(fromUserName);
						textMessage.setFromUserName(toUserName);
						textMessage.setCreateTime(new Date().getTime());
						textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
						textMessage.setFuncFlag(0);
						StringBuffer contentMsg = new StringBuffer();
						String text = String.valueOf(PropertiesUtil.get("contact_text")).trim();
						String msg = new String(text.getBytes("ISO-8859-1"));  
						logger.info("=============================================解析 text"+text+"======================================");
						logger.info("=============================================解析 msg"+msg+"======================================");
						textMessage.setContent("客服小檬工作时间是：周一至周五\ue04a10:00—\ue04c20:00直接发送您的问题就可以得到回复啦！周六日或其他小檬不在线的时间，你也可以通过小檬的个人微信（微信号：lemon0768）找到我哟，欢迎来撩\ue056");
						respMessage = MessageUtil.textMessageToXml(textMessage);
					}
				} else if ("unsubscribe".equals(eventType)) {
					logger.info("======================================用户取消了关注微信公众账号=====================================================");
					UserInfo userInfoN =userService.getUserInfoByOpenId(fromUserName);
					userInfoN.setVersion(userInfoN.getVersion()+1);
					int bool = userService.updateUserInfo(userInfoN);
					logger.info("======================================用户取消了关注微信公众账号=bool:"+bool+"================================================");
				
				}
			}
			// 消息回复
			if ("text".equals(msgType)) {
				logger.info("============ in test start==============================================");
				respMessage = textMsg( requestMap.get("Content"), fromUserName, toUserName, "");
			}

		} catch (Exception e) {
			logger.info("===================================== 解析文件出错==============================");
			//Map<String, String> requestMap = null;
			try {
				requestMap = MessageUtil.parseXml(request);
				// 发送方帐号（open_id）
				String fromUserName = requestMap.get("FromUserName");
				// 公众帐号
				String toUserName = requestMap.get("ToUserName");
				// 消息类型
				String msgType = requestMap.get("MsgType");
				logger.info("===================================== FromUserName："+fromUserName+" ToUserName:"+toUserName+"  msgType:"+msgType+"==============================");
				String contentMsg = null;
				NewsMessage newsMessage = new NewsMessage();
				newsMessage.setToUserName(fromUserName);
				newsMessage.setFromUserName(toUserName);
				newsMessage.setCreateTime(new Date().getTime());
				newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
				newsMessage.setFuncFlag(0);
				// 发送图文消息
				List<Article> articleList = new ArrayList<>();
				Article article1 = new Article();
				article1.setTitle("Hello, Lemon！点击查看新晋檬蜜入门指南");
				article1.setDescription("99元/月，免费撸铁、优惠团操课等你嗨！");
				article1.setPicUrl("https://mmbiz.qlogo.cn/mmbiz_jpg/028ic81tOhdhebltJibFxqPLdlXufL1O45uibIZp3VibQSOZY82z4Yb5mko2z8NXhC4kZEIrbuyIlJ7moPnzwNOicGw/0?wx_fmt=jpeg");
				article1.setUrl("http://mp.weixin.qq.com/s?__biz=MzIyMTQ5MDg2OQ==&mid=100001489&idx=1&sn=6e7871bd945c50cbac2c0026176a035f&chksm=683abd0b5f4d341dc22d5fa26f0907b2b35434c5f052a89707e80c55ac558378cb8abdf21e3f&scene=20#rd");
				articleList.add(article1);
				newsMessage.setArticleCount(articleList.size());
				newsMessage.setArticles(articleList);
				respMessage = MessageUtil.newsMessageToXml(newsMessage);
				logger.info("==============================异常====================================");
				return respMessage;
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			
			
		}
		logger.info("==============================关闭输出流====================================respMessage："+respMessage);
		return respMessage;
	}
	
	/**
	 * 接口测试 
	 * 模拟数据
	 */
	@Override
	public String testInsert() {
		Map<String,String> parMap = new HashMap<>();
		
		parMap.put("fromUserName", "o0r3rwTr11nZygsdVYWKnyyFJg-Y");
		
		parMap.put("toUserName", "gh_16c1ee67d74b");
		parMap.put("EventKey", "11925");
//		parMap.put("EventKey", "qrscene_11925");
		parMap.put("Ticket", "gQGI8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAycWZLdUlSaVpmSDExZzhkYWhwMXkAAgRsgCJZAwScjCcA");
		userScanAttention(parMap,"o0r3rwTr11nZygsdVYWKnyyFJg-Y","s",null);
//		subscribeMsg(parMap,parMap.get("fromUserName") ,"gh_16c1ee67d74b");
//		fristFreeCouponActivitySendMsg("o0r3rwTr11nZygsdVYWKnyyFJg-Y");
		return "";
	}
	
	/**
	 * 在分享的时候判断该分享是否送优惠券
	 * 如果是送优惠券的时候就在对应的用户名下插入优惠券
	 * 
	 * @param couponIds 
	 * @param opendId
	 * @param toUserName
	 * @param channerQrcode
	 * @param numA
	 * @param numI
	 * @param userA
	 * @param userI
	 * @param toUserId
	 * @return
	 */
	public String saveCoupon(String couponIds,String opendId,String toUserName,ChannerQrcode channerQrcode,int numA ,int numI,BigDecimal userA,BigDecimal userI,Integer toUserId){
		logger.info("============================= add coupon start ================================================");
		StringBuffer contentMsg = new StringBuffer();
		Integer invite_friends_channelId = Integer.valueOf(String.valueOf(PropertiesUtil.get("invite_friends_channelId")).trim());
		Integer activityId = Integer.valueOf(String.valueOf(PropertiesUtil.get("invite_friends_activityId")).trim());
		//这里做一个特殊分享的处理
		if(channerQrcode.getId() == 2 || channerQrcode.getId() == invite_friends_channelId){
			logger.info("=============================Friends share parameter:  couponIds"+couponIds+" toUserName:"+toUserName+" channerQrcode:"+channerQrcode+" numA:"+numA+" numI:"+numI +" userA"+userA +" userI"+userI);
			UserInfo userInfoN = userService.getUserInfoByOpenId(opendId);
			UserInfo userInfoI = null ;
			if(userInfoN.getInviterUserid() != null){
				userInfoI = userService.getUserInfoById(userInfoN.getInviterUserid());
			}else if(toUserId > 0){
				userInfoI = userService.getUserInfoById(toUserId);
			}
			// 新的邀请好友插入优惠券
//			if(channerQrcode.getId() == invite_friends_channelId){
//				addCoupon(userInfoN.getId(),activityId);
//				
//			}
			logger.info("==================== to user msg  =============================== ");
			contentMsg.append("欢迎加入檬运动！").append("\n");
			contentMsg.append("您的好友"+userInfoI.getNickName()+"分享的"+numI+"张共"+userI.intValue()+"元的新人代金券将在30分钟内到账。").append("\n");
			contentMsg.append("<a href='"+String.valueOf(PropertiesUtil.get("coupon_urls")).trim()+"'>查看我的代金券</a>").append("\n");
			contentMsg.append("\n");
			contentMsg.append("当您完成第一次锻炼后,"+userInfoI.getNickName()+"也可获得"+numA+"张共"+userA.intValue()+"元的代金券").append("\n");
			contentMsg.append("<a href='"+String.valueOf(PropertiesUtil.get("course_list")).trim()+"'>我要预约课程</a>").append("\n");
			return contentMsg.toString();
		}
		
		UserInfo userInfo = userService.wechatLogin(opendId, null,null, null);
		
		CouponService.Ret_ChangeType rc = null;
		logger.info("============================= couponIds:"+couponIds+"=opendId:"+opendId+"======================");
		// 优惠券id不为空
		int num = 0 ;
		// 有优惠券
		if(couponIds != null && couponIds.length() > 0){
			logger.info("============================= 配置了有优惠券 ================================================");
			String couponId[] = couponIds.split("#");
			if(couponIds.indexOf("#") > 0){
				
				for(String ci:couponId){
					
					logger.info("============================= add one coupon ================================================");
					rc = couponService.addCouponDetail(Integer.valueOf(ci), userInfo.getId(), false);
					if(rc.getIndex() == 0){
						num ++ ;
					}
					logger.info("============================= add one coupon status:="+rc.getValue()+"===============================================");
				}
			}else{
				num = 1;
				rc = couponService.addCouponDetail(Integer.valueOf(couponIds), userInfo.getId(), false);
				logger.info("============================= add one coupon status:="+rc.getValue()+"===============================================");
			}
			String tuis = "欢迎檬蜜【"+channerQrcode.getChannelName()+"】新鲜有趣的小伙伴";
			contentMsg.append(tuis).append("\n");
			contentMsg.append("To Be Lemon, To Be Fresh!").append("\n");
			contentMsg.append("这里没有推销 \ue00F没有硬派 \ue00F没有肌肉狂魔 \ue00F").append("\n");
			contentMsg.append("只有嗨翻天的团操课，").append("\n");
			contentMsg.append("呆萌貌美酷辣帅的教练，精品化的训练营，定制化企业团建课……").append("\n");
			contentMsg.append("").append("\n");
			contentMsg.append("初次见面，<a href='"+String.valueOf(PropertiesUtil.get("coupon_urls")).trim()+"'>小檬送你"+num+"张代金券</a>").append("\n");
			contentMsg.append("").append("\n");
			contentMsg.append("再为您送上<a href='"+String.valueOf(PropertiesUtil.get("mmzn")).trim()+"'>新晋檬蜜入门指南</a>").append("\n");
			contentMsg.append("来！开始檬运动，向内心那个新鲜活力如柠檬的自己说一声，Hello ！").append("\n");
			
		}
		// 没有优惠券
		else{
			logger.info("============================= 没有优惠券 ================================================");
			contentMsg.append("檬蜜【"+channerQrcode.getChannelName()+"】为檬运动代言并为你送上").append("\n");
			contentMsg.append("<a href='"+String.valueOf(PropertiesUtil.get("mmzn")).trim()+"'>新晋檬蜜入门指南</a>").append("\n");
			contentMsg.append("来！开始檬运动，向内心那个新鲜活力如柠檬的自己说一声，Hello ！");
		}
		sendCustomservice(contentMsg.toString(), "text", opendId);
		return contentMsg.toString();
	}
	
	/**
	 * 消息回复方法
	 * @return
	 */
	public String textMsg(String content,String fromUserName,String toUserName,String test){
		String respMessage = null;
		List<Article> articleList = new ArrayList<Article>();
		logger.info("==============================发送图文消息====================================");
		
		TextMessage textMessage = new TextMessage();
		textMessage.setToUserName(fromUserName);
		textMessage.setFromUserName(toUserName);
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
		textMessage.setFuncFlag(0);
		// 由于href属性值必须用双引号引起，这与字符串本身的双引号冲突，所以要转义
		StringBuffer contentMsg = new StringBuffer();
		// 客户输入消息的内容
		if ("照片".equals(content)) {
			contentMsg.append("留下你的邮箱，周一一早，小檬准时为你传送！\ue056").append("\n");
		}else if ("指南".equals(content)) {
			NewsMessage newsMessage = new NewsMessage();
			/*newsMessage.setToUserName(fromUserName);
			newsMessage.setFromUserName(toUserName);
			newsMessage.setCreateTime(new Date().getTime());
			newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
			newsMessage.setFuncFlag(0);
			Article article1 = new Article();
			article1.setTitle("Hello, Lemon！加入檬运动一起下副本打脂肪啦！");
			article1.setDescription("99元/月，免费撸铁、免费团操课等你嗨！");
			article1.setPicUrl("https://mmbiz.qlogo.cn/mmbiz_jpg/028ic81tOhdhebltJibFxqPLdlXufL1O45uibIZp3VibQSOZY82z4Yb5mko2z8NXhC4kZEIrbuyIlJ7moPnzwNOicGw/0?wx_fmt=jpeg");
			article1.setUrl("http://mp.weixin.qq.com/s?__biz=MzIyMTQ5MDg2OQ==&mid=100001489&idx=1&sn=6e7871bd945c50cbac2c0026176a035f&chksm=683abd0b5f4d341dc22d5fa26f0907b2b35434c5f052a89707e80c55ac558378cb8abdf21e3f&scene=20#rd");
			articleList.add(article1);
			newsMessage.setArticleCount(articleList.size());
			newsMessage.setArticles(articleList);
			respMessage = MessageUtil.newsMessageToXml(newsMessage);*/
			return respMessage;
		} else if ("购买会员".equals(content)) {
			/*NewsMessage newsMessage = new NewsMessage();
			newsMessage.setToUserName(fromUserName);
			newsMessage.setFromUserName(toUserName);
			newsMessage.setCreateTime(new Date().getTime());
			newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
			newsMessage.setFuncFlag(0);
			Article article1 = new Article();
			article1.setTitle("Hello, Lemon！加入檬运动一起下副本打脂肪啦！\n");
			article1.setDescription("99元/月，免费撸铁、免费团操课等你嗨！");
			article1.setPicUrl("https://mmbiz.qlogo.cn/mmbiz_jpg/028ic81tOhdhebltJibFxqPLdlXufL1O45uibIZp3VibQSOZY82z4Yb5mko2z8NXhC4kZEIrbuyIlJ7moPnzwNOicGw/0?wx_fmt=jpeg");
			article1.setUrl("http://mp.weixin.qq.com/s?__biz=MzIyMTQ5MDg2OQ==&mid=100001489&idx=1&sn=6e7871bd945c50cbac2c0026176a035f&chksm=683abd0b5f4d341dc22d5fa26f0907b2b35434c5f052a89707e80c55ac558378cb8abdf21e3f&scene=20#rd");
			articleList.add(article1);
			newsMessage.setArticleCount(articleList.size());
			newsMessage.setArticles(articleList);
			respMessage = MessageUtil.newsMessageToXml(newsMessage);*/
			return respMessage;
		}else if("吉祥".equals(content)){
			String url = String.valueOf(PropertiesUtil.get("coach_get_store_pwd")).trim();
			logger.info("=====================================url:"+url+"==============================");
			contentMsg.append("<a href='"+url+"'>来呀点我啊</a>").append("\n");
		}else if("萧枫".equals(content)) {
			String url = String.valueOf(PropertiesUtil.get("meal_log_url")).trim();
			contentMsg.append("<a href='"+url+"'>主人订餐的又来了</a>").append("\n");
		}else{
			logger.info("======================================= 回复空的消息=================================");
			CustomerServiceMessage serviceMsg = new CustomerServiceMessage();
			serviceMsg.setFromUserName(toUserName);
			serviceMsg.setToUserName(fromUserName);
			serviceMsg.setMsgType(MessageUtil.TRANSFER_CUSTOMER_SERVICE);
			respMessage = MessageUtil.newRranInfoMessageToXml(serviceMsg);
			logger.info("======================================= 客服消息："+respMessage+"=================================");
			return respMessage;
			/*return "success";*/
		} 
		
		textMessage.setContent(contentMsg.toString());
		// 将文本消息对象转换成xml字符串
		respMessage = MessageUtil.textMessageToXml(textMessage);
		return respMessage;
	}
	
	
	public void locationTypeMsg(HttpServletRequest request,Map<String, String> requestMap){
		logger.info("===================locationTypeMsg： judge Event is not LOCATION start =======================");
		// xml请求解析
		try {
			logger.info("===================locationTypeMsg： 解析结束=======================");
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			String event = requestMap.get("Event");
			logger.info("===================locationTypeMsg： judge Event is not LOCATION start MsgType:"+msgType+"=======================");
			logger.info("===================locationTypeMsg： judge Event is not LOCATION start fromUserName:"+fromUserName+"=======================");
			logger.info("===================locationTypeMsg： judge Event is not LOCATION start toUserName:"+toUserName+"=======================");
			logger.info("===================locationTypeMsg： judge Event is not LOCATION start event:"+event+"=======================");
			if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)){
				if(event.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION) || event.equals("LOCATION")){
					logger.info("=================== Event is  LOCATION fromUserName:"+fromUserName+" =======================");
					logger.info("===========fromUserName Latitude:"+requestMap.get("Latitude"));
					logger.info("===========fromUserName Longitude:"+requestMap.get("Longitude"));
					logger.info("===========fromUserName Precision:"+requestMap.get("Precision"));
					request.getSession().setAttribute(fromUserName+"_latitude", requestMap.get("Latitude"));
					request.getSession().setAttribute(fromUserName+"_longitude", requestMap.get("Longitude"));
					request.getSession().setAttribute(fromUserName+"_precision", requestMap.get("Precision"));
					Map<String,Object> map = new HashMap<>();
					String openId = fromUserName;
					map.put("latitude", requestMap.get("Latitude"));
					map.put("longitude", requestMap.get("Longitude"));
					map.put("precision", requestMap.get("Precision"));
					request.getSession().setAttribute(openId,map);
					Object obj = request.getSession().getAttribute(openId);
					userPositionRedisDao.addUserPosition(fromUserName, map);
					logger.info("=================== Event is  LOCATION  end openId："+openId+"==obj:"+obj+"=====================");
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("=================== locationTypeMsg error:"+e.getMessage()+"=======================");
		}

		
	}
	
	/**
	 * 用户关注
	 * @param requestMap
	 * @param fromUserName
	 * @param toUserName
	 * @return
	 */
	public String subscribeMsg(Map<String,String> requestMap,String fromUserName,String toUserName,HttpServletResponse response, HttpServletRequest request){
		
		logger.info("================================subscribeMsg  start =========================");
		String respMessage = "";// 返回消息字符串 xml类型的 
		ActivityInfo activityInfo = activityInfoMapper.selectById(1);
		logger.info("===========================================用户关注了微信公众账号=================requestMap EventKey:=====================");
		String qrscene = requestMap.get("EventKey");
		String ticket = requestMap.get("Ticket");
		logger.info("====================================get EventKey qrscene:"+qrscene+" ========================================");
		logger.info("====================================get Ticket ticket:"+ticket+" ========================================");
		
		UserInfo userInfo = userService.getUserInfoByOpenId(fromUserName);
		// 在关注微信公众账号之前该用户有一笔订单 在他关注微信公众账号的时候回将他最近一笔的订单流水号带过来
		if (qrscene.split("_").length>2){
			logger.error("=====================processRequestNew error===qrscene:" +qrscene+"===============================");
			qrscene = "";
		}
		
		// 判断用户扫描的二维码是否带了参数
		// 不带参数的二维码 有可能是直接搜索出来关注的也可能是别的地方搜出来关注的
		// 关注公众账号是否是通过带参数的二维码 
		if(qrscene.length() == 0){
			logger.info("=============================首次关注公众账号 未通过渠道关注===============================");
			// 首次用户
			if(userInfo == null){
				logger.info("=============================小白用户关注===============================");
				// 插入 
				logger.info("===================user is null insert userInfo data =================================");
				userInfo = userService.wechatLogin(fromUserName, null, null, null);
			}else{
				// 邀请好友送券的默认回复消息
				logger.info("=============================首次关注的用户 InviterUserid"+userInfo.getInviterUserid()+"===============================");
				if(userInfo.getInviterUserid() != null){
					logger.info("=============================首次关注的用户 version"+userInfo.getVersion()+" "+(userInfo.getVersion() == 0)+"===============================");
					UserInfo shareUserInfo = userService.getUserInfoById(userInfo.getInviterUserid());
					if(userInfo.getVersion() == 0){
						logger.info("=============================首次关注的用户===============================");
						invitingFriendsMsg(shareUserInfo, 1, userInfo.getOpenid());
						
					}else{
						logger.info("=============================取消关注的用户通过邀请好友再次关注微信公众账号===============================");
						// 判断用户领取过但是未使用的优惠券的时候就发送客服消息
						if(activityInfo != null){
							String coupons = activityInfo.getInviteCouponId();
							List<String> couponList = Arrays.asList(coupons.split("#"));
							Integer count = couponDetailMapper.queryUserHasCountByUsed(userInfo.getId(), couponList, 0);
							if(count == couponList.size()){
								invitingFriendsMsg(shareUserInfo, 1, userInfo.getOpenid());
							}
						}
					}
					
				}
				// 关注之后再取消的用户
				else if(userInfo != null && userInfo.getVersion() == 1){
					logger.info("=============================该用户取消了之后再次关注我们的公众账号 只发送默认回复消息===============================");
				}
			}
			userInfo.setSubscribe(1);
			int bool = userService.updateUserInfo(userInfo);
			logger.info("===================update user data bool :"+bool+"=================================");
			request.getSession().setAttribute("USER_INFO",userInfo);
			request.getSession().setAttribute("USER_ID",userInfo.getId());


//			textMessage.setContent(contentMsg.toString());
			// 将文本消息对象转换成xml字符串
//			respMessage = MessageUtil.textMessageToXml(textMessage);
			return respMessage;
			
		}else{
			// 带参数的二维码
			String id = qrscene.split("_")[1];
			logger.info("=============================qrscene: "+qrscene+" ==》》id:"+id+"==============");
			logger.info("=============================ticket: "+ticket+"==============================");
			ChannerQrcode channerQrcode = null;//channerQrcodeMapper.queryChannerQrcodeById(Integer.valueOf(id));
			channerQrcode = channerQrcodeMapper.queryChannerQrcodeByIdAndTicket(Integer.valueOf(id), ticket);
			// 获取配置文件中的渠道Id用于邀请好友计算带量
			Integer channerId = Integer.valueOf(String.valueOf(PropertiesUtil.get("invite_friends_channelId")).trim());
			Integer activityId = 1 ;// 获取配置文件中的邀请好友Id 用于赠送用户优惠券,这里给的默认值是旧的邀请好友的活动id
			Integer inviteeUserId = 0 ;// 邀请者的Id
			boolean isNowUser = true;// 判断是否是新用户
			Map<String,Object> isNowUserMap = new HashMap<>();
			
			// 永久二维码
			if(channerQrcode != null){
				logger.info("=============================通过渠道二维码进入的微信公众账号===============================");
				channerQrcode.setNumber(channerQrcode.getNumber()+1);
				//1先查询
				ChannerDetailed channerDetailed = channerDetailedMapper.queryChannerDetailedByOpendId(fromUserName);
				UserInfo userInfoNew = userInfoMapper.selectByOpenid(fromUserName);
				
				// 判断是通过点击旧的邀请好友链接进来的还是通过面对面分享进来的或者是渠道二维码关注进来的
				// 如果是点击旧的链接进来的话该用户是先插入用户信息的面对面分享和渠道二维码进来的是没有用户信息的
				
				// 判断用户是否是关注过我们微信公众账号
				if(channerDetailed == null && userInfoNew == null){
					logger.info("=============================首次关注公众账号插入渠道明细信息 start===============================");
					
					addOrUpdateChannerDetailed(channerQrcode.getId(), fromUserName, null);
					int bool = channerQrcodeMapper.updateChannerQrcode(channerQrcode);
					logger.info("=============================首次关注公众账号插入渠道明细信息 end=======bool:"+bool+"========================");
					// 当用户不存在的时候插入一条用户信息
					if(userInfo == null){
						// 插入 
						logger.info("===================user is null insert userInfo data =================================");
						userInfo = userService.wechatLogin(fromUserName, null, null, null);
					}
					userInfo.setSubscribe(1);
					int bool1 = userService.updateUserInfo(userInfo);
					logger.info("===================update user data bool1 :"+bool1+"=================================");
					// 插入 优惠券
					String msgs = saveCoupon(channerQrcode.getCouponId(),fromUserName,toUserName,channerQrcode,0,0,BigDecimal.valueOf(0),BigDecimal.valueOf(0),inviteeUserId);
					
				}else{
					
					// 通过邀请好友的渠道进入微信公众账号
					if(userInfoNew != null && userInfoNew.getVersion() == 0 
							&& userInfoNew.getInviterUserid() > 0 && channerDetailed == null){
						
						addOrUpdateChannerDetailed(channerQrcode.getId(), fromUserName, null);
						int bool = channerQrcodeMapper.updateChannerQrcode(channerQrcode);
						logger.info("=============================首次关注公众账号插入渠道明细信息 end=======bool:"+bool+"========================");
						// 当用户不存在的时候插入一条用户信息
						if(userInfo == null){
							// 插入 
							logger.info("===================user is null insert userInfo data =================================");
							userInfo = userService.wechatLogin(fromUserName, null, null, null);
						}
						userInfo.setSubscribe(1);
						int bool2 = userService.updateUserInfo(userInfo);
						logger.info("===================update user data bool2 :"+bool2+"=================================");
						// 插入 优惠券
						UserInfo shareUserInfo = userInfoMapper.selectById(userInfo.getInviterUserid());
						invitingFriendsMsg(shareUserInfo, activityId, fromUserName);
						
					}
					logger.info("================================================渠道二维码取消关注了再次关注=====================");
					// 判断用户领取过但是未使用的优惠券的时候就发送客服消息
					if(activityInfo != null){
						// 插入 优惠券
						UserInfo shareUserInfo = userInfoMapper.selectById(userInfo.getInviterUserid());
						String coupons = activityInfo.getInviteCouponId();
						List<String> couponList = Arrays.asList(coupons.split("#"));
						Integer count = couponDetailMapper.queryUserHasCountByUsed(userInfo.getId(), couponList, 0);
						if(count == couponList.size()){
							invitingFriendsMsg(shareUserInfo, 1, userInfo.getOpenid());
						}
					}
				}
			}else{
				// 如果不是永久二维码关注就来的用户那么就是临时二维码关注进来的
				logger.info("============================= 临时二维码关注进来的用户 ==============================");
				if(userInfo == null){
					// 插入 
					logger.info("===================user is null insert userInfo data =================================");
					userInfo = userService.wechatLogin(fromUserName, null, null, null);
				}
				channerQrcode = channerQrcodeMapper.queryChannerQrcodeById(channerId);
				
				activityId = Integer.valueOf(String.valueOf(PropertiesUtil.get("invite_friends_activityId")).trim());
				inviteeUserId = Integer.valueOf(id);
				// 这里判断该用户是否是全新的用户
				UserInfo shareUserInfo = userInfoMapper.selectById(inviteeUserId);
				isNowUserMap = userService.isNewCustomOrInsert(fromUserName, userInfo, activityId, shareUserInfo);
				isNowUser = (boolean) isNowUserMap.get("bool");
				// 不是全新的用户所以没有送券
				if(!isNowUser){
					logger.info("=================== this user is not now ===================");
					respMessage = defaultMsg(fromUserName, toUserName);
					return respMessage;
				}
				
				ChannerDetailed channerDetailed = null;
				channerDetailed = channerDetailedMapper.queryChannerDetailedByOpendId(fromUserName);
				if(channerDetailed == null){
					channerQrcode.setNumber(channerQrcode.getNumber()+1);
				}
				addOrUpdateChannerDetailed(channerQrcode.getId(), fromUserName, channerDetailed);
				// 更新渠道信息 表示用户
				int bool = channerQrcodeMapper.updateChannerQrcode(channerQrcode);
				// 表示是新用户 因为未拥有正常订单或者是领取过本次活动的优惠券的用户全部都算是新用户
				// 插入 优惠券
				invitingFriendsMsg(shareUserInfo, activityId, fromUserName);
				
			}
			
		}
		
		// 当用户不存在的时候插入一条用户信息
		if(userInfo == null){
			// 插入 
			logger.info("===================user is null insert userInfo data =================================");
			userInfo = userService.wechatLogin(fromUserName, null, null, null);
		}
		if(userInfo.getSubscribe() != 1){
			userInfo.setSubscribe(1);
			int bool = userService.updateUserInfo(userInfo);
			logger.info("===================update user data bool :"+bool+"=================================");
		}

		request.getSession().setAttribute("USER_INFO",userInfo);
		request.getSession().setAttribute("USER_ID",userInfo.getId());

		logger.info("=============================默认消息===============================");
		//respMessage = MessageUtil.textMessageToXml(textMessage);
		respMessage = defaultMsg(fromUserName, toUserName);
		logger.info("==============================用户关注了微信公众账号 respMessage1==" + respMessage +"=======================");
		return respMessage;
	}
	
	// 默认回复 消息
	public String defaultMsg(String fromUserName,String toUserName){
		String respMessage = "";
		/*NewsMessage newsMessage = new NewsMessage();
		newsMessage.setToUserName(fromUserName);
		newsMessage.setFromUserName(toUserName);
		newsMessage.setCreateTime(new Date().getTime());
		newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
		newsMessage.setFuncFlag(0);*/
		StringBuffer sb = new StringBuffer();
//		String content = "Hey，恭喜你找到了组织！<br>[ 动吃动吃动吃星球 ]<br>这是围裙私教为你私人建造<br><br>*不怕你好吃，就怕你不会吃<br>*不怕你身材不好，就怕你身材不好还懒<br><br>新手 l 饮食 <br>增肌 l 减肥 <br>私教 l 团体课<br>在这里总有你想不到的惊喜";
		sb.append("Hey，恭喜你找到了组织！").append("\n")
		.append("[ 动吃动吃动吃星球 ]").append("\n")
		.append("这是围裙健身为你私人建造").append("\n\n")
		.append("*不怕你好吃，就怕你不会吃").append("\n")
		.append("*不怕你身材不好，就怕你身材不好还懒").append("\n\n")
		.append("新手 | 饮食").append("\n")
		.append("增肌 | 减肥").append("\n")
		.append("私教 | 团体课").append("\n")
		.append("在这里总有你想不到的惊喜");
		// 发送图文消息
		List<TextMessage> articleList = new ArrayList<>();
		TextMessage textMessage = new TextMessage();
		textMessage.setToUserName(fromUserName);
		textMessage.setFromUserName(toUserName);
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
		textMessage.setFuncFlag(0);
		textMessage.setContent(sb.toString());
		
		
		// 图文1
       /* Article article1 = new Article();
        article1.setTitle("运动？从了解自身起航，19元专业体测比你更了解你自己");
        article1.setDescription("");
        article1.setPicUrl("http://gorun-h5-image.oss-cn-shenzhen.aliyuncs.com/passage1.jpg");
        article1.setUrl("http://mp.weixin.qq.com/s?__biz=MzIyMTQ5MDg2OQ==&mid=2247486158&idx=1&sn=3925513b29c2c97b657c92edbc044f13&chksm=e83ab114df4d38028f6c12ba9a494b0570d8174083248d4e67f9b3774e3b50e054d1af33ac9a&mpshare=1&scene=1&srcid=0905Hg5EaN6lKgT7qH8JK77j#rd");
        articleList.add(article1);*/
        
        /*// 图文2
        Article article2 = new Article();
        article2.setTitle("檬运动新平台使用攻略 | 你还在等什么？");
        article2.setDescription("");
        article2.setPicUrl("http://gorun-h5-image.oss-cn-shenzhen.aliyuncs.com/passage2.jpg");
        article2.setUrl("http://mp.weixin.qq.com/s?__biz=MzIyMTQ5MDg2OQ==&mid=2247486158&idx=2&sn=139f805686ebb00f29cd6ae04f0ad9f5&chksm=e83ab114df4d3802914c395b13d0339856ff4212e2e3ed650b31b783bcee933394ae0b083fd8&mpshare=1&scene=1&srcid=0905mMYkd3pZlgDpOa9pNZOr#rd");
        articleList.add(article2);*/
		
		/*newsMessage.setArticleCount(articleList.size());
		newsMessage.setArticles(articleList);
		respMessage = MessageUtil.newsMessageToXml(newsMessage);*/
		respMessage = MessageUtil.textMessageToXml(textMessage);
		return respMessage;
	}
	
	public String clickMsg(Map<String,String> requestMap,String fromUserName,String toUserName){
		String eventKey = requestMap.get("EventKey");
		String respMessage = null;
		logger.info("===========================================用户点击微信公众账号菜单事件====eventKey：" + eventKey+ "=====================================================");
		// 点击联系小檬
		if("lxxm".equals(eventKey)){
			TextMessage textMessage = new TextMessage();
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setFuncFlag(0);
			StringBuffer contentMsg = new StringBuffer();
			textMessage.setContent("客服小檬工作时间是：周一至周五\ue04a10:00—\ue04c20:00直接发送您的问题就可以得到回复啦！周六日或其他小檬不在线的时间，你也可以通过小檬的个人微信（微信号：lemon0768）找到我哟，欢迎来撩\ue056");
			respMessage = MessageUtil.textMessageToXml(textMessage);
		}
		return respMessage;
	}
	
	/**
	 * 获取邀请好友的时候送的优惠券金额和张数
	 * @param activityId
	 * @return
	 */
	public Map<String,Object> getActivityData(Integer activityId){
		logger.info("================= getActivityData satrt activityId:"+activityId+"=============================");
		ActivityInfo activityInfo = activityInfoMapper.selectById(activityId);
		CouponInfo couponInfo = null;
		Map<String,Object> parMap = new HashMap<>();
		BigDecimal userAmount = new BigDecimal(0) ;// 被邀请者可获得金额
		BigDecimal shareUserAmount = new BigDecimal(0) ;// 邀请者可获得金额
		int userCouponCount = 0 ;// 被邀请者可获得优惠券数量
		int shareCouponCount = 0 ;// 邀请者可获得的优惠券数量
		if(activityInfo != null){
			String couponIds =  activityInfo.getCouponId();
			String couponId[] = couponIds.split("#");
			// 先是判断 邀请id 是否多个
			if(couponIds.indexOf("#")>0){
				for(String ids:couponId){
					couponInfo = couponInfoMapper.selectById(Integer.valueOf(ids));
					shareUserAmount = shareUserAmount.add(couponInfo.getCashMoney());
					shareCouponCount ++;
				}
			}else{
				couponInfo = couponInfoMapper.selectById(Integer.valueOf(couponIds));
				shareUserAmount = shareUserAmount.add(couponInfo.getCashMoney());
				shareCouponCount = 1;
			}
			String inviteCouponId = activityInfo.getInviteCouponId();
			String[] inviteCouponIds = inviteCouponId.split("#");
			// 先是判断 被邀请id 是否多个
			if(inviteCouponId.indexOf("#")>0){
				for(String ids:inviteCouponIds){
					couponInfo = couponInfoMapper.selectById(Integer.valueOf(ids));
					userAmount = userAmount.add(couponInfo.getCashMoney());
					userCouponCount ++;
				}
			}else{
				couponInfo = couponInfoMapper.selectById(Integer.valueOf(inviteCouponId));
				userAmount = userAmount.add(couponInfo.getCashMoney());
				userCouponCount = 1;
			}
			
		}
		parMap.put("userAmount", userAmount);
		parMap.put("shareUserAmount", shareUserAmount);
		parMap.put("userCouponCount", userCouponCount);
		parMap.put("shareCouponCount", shareCouponCount);
		logger.info("================= getActivityData====>> userAmount:"+userAmount+" userCouponCount:"+userCouponCount
				+"  shareUserAmount:"+shareUserAmount+"  shareCouponCount:"+shareCouponCount+"======");
		logger.info("================= getActivityData end =============================");
		return parMap;
	}
	
	/**
	 * 添加优惠券
	 * @param userId
	 * @param  @param activitId
	 */
	public void addCoupon(Integer userId,Integer activitId){
		logger.info("======================= 面对面扫码邀请好友送 优惠券 start=============");
		// 获取活动的Id
		ActivityInfo activityInfo = activityInfoMapper.selectById(activitId);
		// 判断该活动Id获取活动有哪些优惠券
		CouponService.Ret_ChangeType ret_changetype =  couponService.addCouponDetailByActivityId(activitId, userId);
		logger.info("======================= 面对面扫码邀请好友送 优惠券 >>> "+ret_changetype.getValue()+"=============");
		logger.info("======================= 面对面扫码邀请好友送 优惠券 end=============");
	}
	
	/**
	 * 扫描关注
	 * 已关注的二维码 
	 * @param requestMap
	 * @param fromUserName 用户的opendId
	 * @param toUserName 微信公众账号的Id
	 * @return
	 */
	public String userScanAttention(Map<String,String> requestMap,String fromUserName,String toUserName,HttpServletResponse response){
		logger.info("===========================================userScanAttention start======================================");
		String qrscene = requestMap.get("EventKey");
		String ticket = requestMap.get("Ticket");
		logger.info("====================================get EventKey qrscene:"+qrscene+" ========================================");
		logger.info("====================================get Ticket ticket:"+ticket+" ========================================");
		// 先判断 里面的参数是否是永久二维码
		Integer channerId = 0 ;
		Integer invite_friends_channelId = Integer.valueOf(String.valueOf(PropertiesUtil.get("invite_friends_channelId")).trim());
		Integer activityId = Integer.valueOf(String.valueOf(PropertiesUtil.get("invite_friends_activityId")).trim());
		UserInfo userInfo = null;// 被邀请者
		UserInfo shareUserInfo = null;// 邀请者
		Map<String,Object> parMap = new HashMap<>();
		String respMessage = "";// 回复消息
		try {
			// 判断二维码参数是整数的还是字符串的
			if(isNumeric(qrscene)){
				channerId = Integer.valueOf(qrscene);
				// 再次判断是否是数据库中存在的永久二维码还是临时二维码
				ChannerQrcode channerQrcode = null;
				channerQrcode = channerQrcodeMapper.queryChannerQrcodeByIdAndTicket(channerId, ticket);  
				// 在数据库中查不到的全部默认为是临时二维码
				if(channerQrcode == null){
					// 如果是临时二维码 里面的参数就是发起邀请者的Id
					Integer userId = channerId;
					userInfo = userInfoMapper.selectByOpenid(fromUserName);
					shareUserInfo = userInfoMapper.selectById(userId);
					// 当用户不存在的时候插入一条用户信息
					if(userInfo == null){
						// 插入 
						logger.info("===================user is null insert userInfo data =================================");
						userInfo = userService.wechatLogin(fromUserName, null, null, null);
						userInfo.setSubscribe(1);
						userService.updateUserInfo(userInfo);
					}
					// 只要其中一个为空就回复默认消息
					if(shareUserInfo == null){
						logger.info("=============userScanAttention is not find  userInvite================");
					}else{
						if(userInfo.getSubscribe() != 0){
							userInfo.setSubscribe(1);
							userService.updateUserInfo(userInfo);
						}
						// 是新用户 赠送优惠券
						// 先插入一张临时的中间表
						Integer addInviteCouponCount = inviteCouponService.addInviteCouponByUserIdAndActivityId(userInfo.getId(), activityId, shareUserInfo.getId());
						if(addInviteCouponCount < 1){
							return "";
						}
						channerQrcode = channerQrcodeMapper.queryChannerQrcodeById(invite_friends_channelId);
						// 插入带量信息 一遍计算该渠道带来的用户有哪些
						ChannerDetailed channerDetailed = null;
						channerDetailed = channerDetailedMapper.queryChannerDetailedByOpendId(fromUserName);
						if(channerDetailed == null){
							channerQrcode.setNumber(channerQrcode.getNumber()+1);
							channerQrcodeMapper.updateChannerQrcode(channerQrcode);
						}
						addOrUpdateChannerDetailed(channerQrcode.getId(), fromUserName, channerDetailed);// 修改用户关注渠道明细
						invitingFriendsMsg(shareUserInfo, activityId, userInfo.getOpenid());// 给用户发送客服消息 送了几张优惠券总金额是多少
					}
				}
			}else{
				logger.info("===============userScanAttention is not invite friends activity======================================");
				return "";
			}
		} catch (Exception e) {
			logger.error("============userScanAttention error :"+e.getMessage()+"====================================");
		}
		logger.info("========================userScanAttention end ======================================");
		return "";
	}
	
	/**
     * 利用正则表达式判断字符串是否是数字
     * @param str
     * @return
     */
    public boolean isNumeric(String str){
           Pattern pattern = Pattern.compile("[0-9]*");
           Matcher isNum = pattern.matcher(str);
           if( !isNum.matches() ){
               return false;
           }
           return true;
    }
    
    public void addActivityUser(Integer activityId,Integer userId,Integer inviteUserid){
    	logger.info("======================= addActivityUser start ===================");
    	ActivityUser activityUser = new ActivityUser();
    	activityUser.setActivityId(activityId);
    	activityUser.setUserid(userId);
    	activityUser.setInviteUserid(inviteUserid);
    	activityUser.setIsGetedCoupon(0);
    	activityUser.setCreateTime(new Date());
    	activityUser.setCreateBy(userId+"");
    	Integer bool = activityUserMapper.insertSelective(activityUser);
    	logger.info("======================= addActivityUser bool: "+bool+"===================");
    	logger.info("======================= addActivityUser end ===================");
    }
	//TODO: 未完成
    /**
     * 用户关注微信公众账号方法重构
     * @param requestMap
     * @param fromUserName
     * @param toUserName
     * @return
     */
	public String subscribeMsgNew(Map<String, String> requestMap, String fromUserName, String toUserName) {
		logger.info("========================subscribeMsgNew 用户关注了微信公众账号             start  ======================");
		logger.info("========================subscribeMsgNew parameter: fromUserName= "+fromUserName+"  toUserName="+toUserName+"======");
		try {
			String qrscene = requestMap.get("EventKey");
			String ticket = requestMap.get("Ticket");
			logger.info("====================================subscribeMsgNew get EventKey qrscene:" + qrscene+ " ========================================");
			logger.info("====================================subscribeMsgNew get Ticket ticket:" + ticket+ " ========================================");
			// 先判断用户是否存在
			UserInfo userInfo = userInfoMapper.selectByOpenid(fromUserName);
			// 1 用户不存在
			if (userInfo == null) {
				// 查看关注的时候是否带有参数
				// 在关注微信公众账号之前该用户有一笔订单 在他关注微信公众账号的时候回将他最近一笔的订单流水号带过来
				if (qrscene.split("_").length>2){
					logger.error("=====================processRequestNew error===qrscene:" +qrscene+"===============================");
					qrscene = "";
				}
				
			} else {
			// 2 用户存在
				
			}
		} catch (Exception e) {
		}
		
		return null;
	}
	
	/**
	 * 客服回复消息
	 * @param msg 回复的消息
	 * @param msgType 消息的类型 这里暂时只是做文本回复
	 * @param opendId 用户的opendId 
	 */
	@Override
	public void sendCustomservice(String msg, String msgType, String opendId) {
		logger.info("============================= sendCustomservice send to "+opendId+" start ======================");
		msg = msg.replace("\n", "\\n");
		Map<String,Object> sendMap = new HashMap<>();
		// 文本消息类型
		if("text".equals(msgType)){
			sendMap = CustomserviceUtil.senTextMsg(tokenMapper.selectTokenByKey("access_token").getToken(), msg,opendId);
		}
		logger.info("============================= sendCustomservice send to "+opendId+" status is  "+sendMap.get("errmsg")+"   end ======================");
	}
	
	/**
	 * 邀请好友回复默认消息
	 * @param shareUserInfo 邀请者
	 * @param activityId 活动ID
	 * @param foUserOpendId 用户OpendId
	 * @return
	 */
	public void invitingFriendsMsg(UserInfo shareUserInfo,Integer activityId,String foUserOpendId){
		logger.info("============================ invitingFriendsMsg start   ==============================");
		logger.info("============================ invitingFriendsMsg parameter： ============================");
		logger.info("========================================================shareUserInfo:"+shareUserInfo.getOpenid()+"  activityId:"+activityId +"foUserOpendId"+foUserOpendId);
		try {
			ActivityInfo activityInfo = activityInfoMapper.selectById(activityId);
			CouponInfo couponInfo = null;
			Map<String,Object> parMap = new HashMap<>();
			BigDecimal userAmount = new BigDecimal(0) ;// 被邀请者可获得金额
			BigDecimal shareUserAmount = new BigDecimal(0) ;// 邀请者可获得金额
			int userCouponCount = 0 ;// 被邀请者可获得优惠券数量
			int shareCouponCount = 0 ;// 邀请者可获得的优惠券数量
			if(activityInfo != null){
				String couponIds =  activityInfo.getCouponId();
				String couponId[] = couponIds.split("#");
				// 先是判断 邀请id 是否多个
				if(couponIds.indexOf("#")>0){
					for(String ids:couponId){
						couponInfo = couponInfoMapper.selectById(Integer.valueOf(ids));
						shareUserAmount = shareUserAmount.add(couponInfo.getCashMoney());
						shareCouponCount ++;
					}
				}else{
					couponInfo = couponInfoMapper.selectById(Integer.valueOf(couponIds));
					shareUserAmount = shareUserAmount.add(couponInfo.getCashMoney());
					shareCouponCount = 1;
				}
				String inviteCouponId = activityInfo.getInviteCouponId();
				String[] inviteCouponIds = inviteCouponId.split("#");
				// 先是判断 被邀请id 是否多个
				if(inviteCouponId.indexOf("#")>0){
					for(String ids:inviteCouponIds){
						couponInfo = couponInfoMapper.selectById(Integer.valueOf(ids));
						userAmount = userAmount.add(couponInfo.getCashMoney());
						userCouponCount ++;
					}
				}else{
					couponInfo = couponInfoMapper.selectById(Integer.valueOf(inviteCouponId));
					userAmount = userAmount.add(couponInfo.getCashMoney());
					userCouponCount = 1;
				}
				
			}
			StringBuffer contentMsg = new StringBuffer();
			contentMsg.append("欢迎加入檬运动！").append("\n");
			contentMsg.append("您的好友"+shareUserInfo.getNickName()+"分享的"+userCouponCount+"张共"+userAmount.intValue()+"元的新人代金券将在30分钟内到账。").append("\n");
			contentMsg.append("<a href='"+String.valueOf(PropertiesUtil.get("coupon_urls")).trim()+"'>查看我的代金券</a>").append("\n");
			contentMsg.append("\n");
			contentMsg.append("当您完成第一次锻炼后,"+shareUserInfo.getNickName()+"也可获得"+shareCouponCount+"张共"+shareUserAmount.intValue()+"元的代金券").append("\n");
			contentMsg.append("<a href='"+String.valueOf(PropertiesUtil.get("course_list")).trim()+"'>我要预约课程</a>").append("\n");
			this.sendCustomservice(contentMsg.toString(), "text",foUserOpendId);// 以客服的身份给用户发送消息
		} catch (Exception e) {
			logger.error("============================ invitingFriendsMsg error :"+e.getMessage()+" ==============================");
		}
		logger.info("============================ invitingFriendsMsg end   ==============================");
	}
	
	/**
	 * 添加获取修改用户渠道明细
	 * @param channerId 渠道Id
	 * @param fromUserName 用户opendId
	 * @param channerDetailed 用户渠道明细
	 */
	public void addOrUpdateChannerDetailed(Integer channerId,String fromUserName,ChannerDetailed channerDetailed){
		logger.info("====================================== addOrUpdateChannerDetailed  start ================================");
		try {
			if(channerDetailed == null || (channerDetailed != null && channerDetailed.getId() < 1)){
				channerDetailed = new ChannerDetailed();
				logger.info("====================================== addOrUpdateChannerDetailed  insert in to  ================================");
				channerDetailed.setChannerId(channerId);
				channerDetailed.setOpenid(fromUserName);
				channerDetailed.setCreatedTime(new Date());
				int insertCount = channerDetailedMapper.insertChannerDetailed(channerDetailed);
				logger.info("====================================== addOrUpdateChannerDetailed  insert in to count  :"+insertCount+" ================================");
			}else{
				logger.info("====================================== addOrUpdateChannerDetailed  update  ================================");
				channerDetailed.setChannerId(channerId);
				int updateCount = channerDetailedMapper.updateChannerDetailed(channerDetailed);
				logger.info("====================================== addOrUpdateChannerDetailed  update  count  :"+updateCount+" ================================");
			}
			
		} catch (Exception e) {
			logger.error("====================================== addOrUpdateChannerDetailed  error:"+e.getMessage()+" ================================");
		}
		logger.info("====================================== addOrUpdateChannerDetailed  end ================================");
	}
	
	/**
	 * 赠送私教优惠券活动 推送文本消息
	 * 
	 * @param foromUserName
	 */
	public void fristFreeCouponActivitySendMsg(String fromUserName){
		// 即将推送的文本消息
		StringBuffer contentMsg = new StringBuffer();
		contentMsg.append("开始运动？从了解自己的身体开始！").append("\n");
		contentMsg.append("小檬将两张30元现金券揣入你的怀中，带你低价体验全方位的身体测评和专业的私教体验课程。").append("\n");
		contentMsg.append("\n");
		contentMsg.append("<a href='"+String.valueOf(PropertiesUtil.get("home_page_url")).trim()+"'>点击了解详情</a>").append("\n");
		UserInfo userInfo = userService.getUserInfoByOpenId(fromUserName);
		// step 1 用户不存在就插入用户
		if(userInfo == null){
			userInfo = userService.wechatLogin(fromUserName, null, null, null);
		}
		// step 2  获取活动 Id
		Integer activityId = null;
		List<DataDict> dataDictList = dataDictService.queryDataDicts(DataDictConstants.FREE_COUPON_ACTIVITY_ID);

		if (dataDictList != null) {
			DataDict dataDict = dataDictList.get(0);
			if (dataDict != null) {
				activityId = Integer.valueOf(dataDict.getDictCode());
			}
		}
		// step 3 配置活动ID，才发生
		if (activityId != null) {
			// step 4  查看一下活动下面的优惠券用户是否拥有
			ActivityInfo activityInfo = activityInfoMapper.selectById(activityId);
			if(activityInfo != null && "1".equals(activityInfo.getStatus())){
				String coupons = activityInfo.getCouponId();
				List<String> couponList = Arrays.asList(coupons.split("#"));
//				Integer count = couponDetailMapper.queryUserHasCountByUsed(userInfo.getId(), couponList, null);

                // 发送模板消息的规则是只要是还未使用完全的优惠券就会发送模板消息
                // 直接搜索微信公众账号进来的用户是还未领取优惠券的
                Integer userHaveActivityCouponCount = couponDetailMapper.queryUserHasCountByUsed(userInfo.getId(), couponList, null);// 获取该用户拥有本次活动的优惠券
                Integer userNotUsedActivityCouponCount = couponDetailMapper.queryUserHasCountByUsed(userInfo.getId(), couponList, 0);// 用户未使用本次活动赠送优惠券的数量
                if(couponList.size() > 0 ) {// 表示本次活动赠送优惠券
                    // 未领取的用户 ，只要是未拥有的这次活动优惠券的用户全部默认为是新用户是需要发送模板消息的
                    if (userHaveActivityCouponCount == 0) {
                        this.sendCustomservice(contentMsg.toString(), "text", fromUserName);// 以客服的身份给用户发送消息
                    } else {
                        // 已领取了优惠券
                        // 未全部使用
                        if (userNotUsedActivityCouponCount > 0) {
                            this.sendCustomservice(contentMsg.toString(), "text", fromUserName);// 以客服的身份给用户发送消息
                        }
                        // 已全部使用
                    }
                }
//				if(count != couponList.size()){
//					this.sendCustomservice(contentMsg.toString(), "text",fromUserName);// 以客服的身份给用户发送消息
//				}
			}
			
		}
		
		
	}
}
